#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''eof
name:最近3个月订烟额总下降比率过大
code:OrderAmount_FallingRate_Check_1
tableName:
columnName:
groups:准入>烟商
dependencies:BTM
type:常用指标
dataSourceType:在线指标
description:
eof'''


'''
最近三个月 四个月 都找出，然后判断 第四个月是否存在
然后计算
若第四个月为空，则算三个月
若前三个月中为空，则返回-999999
若前三个月中有分母为0 则排除 (exp：100,0,100-> -1)，计算剩下的ratio
'''
import sys
import pandas as pd
import datetime
import numpy as np

reload(sys)
sys.setdefaultencoding('utf-8')


def Rule53_OrderAmount_FallingRate_Check_1():
    null_type_list = ['', None, 'null', 'Null', '/']
    money_month = {'T4':[], 'T3':[], 'T2':[], 'T1':[]}
    sum_money = []

    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_days_list = [(ApplTime - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [120, 90, 60, 30, 0]]
        else:
            last_year_days_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i)).strftime('%Y%m%d') \
                                   for i in [120, 90, 60, 30, 0]]
    except:
        return -999999

    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >=1 :
            for i in BTM_['indent'] :
                if i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                    and i.has_key('indentMoney') and i['indentMoney'] not in null_type_list \
                        and isfloat(i['indentMoney']) \
                        and Formate(i['indentDate']) is not None:
                    #对所有数据进行最近三个月匹配 T1倒推1月 T2倒推2月 T3倒推3月 T4倒推4月
                    if Formate(i['indentDate']) > last_year_days_list[0] and Formate(i['indentDate']) <= last_year_days_list[1]:
                        money_month['T4'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[1] and Formate(i['indentDate']) <= last_year_days_list[2]:
                        money_month['T3'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[2] and Formate(i['indentDate']) <= last_year_days_list[3]:
                        money_month['T2'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[3] and Formate(i['indentDate']) <= last_year_days_list[4]:
                        money_month['T1'].append(float(i['indentMoney']))
            #排序按T1 T2 T3 T4排序
            keys = sorted(money_month)

            #对T4 T3 T2 T1 进行判断
            #if T4 = [] T3,T2,T1!=[],对T3 T2 T1 求下降额
            #if T3,T2,T1 任意为空 返回缺失
            if money_month['T4'] == []:
                for k in keys[0:3]:
                    if money_month[k]!=[]:
                        sum_money.append(sum(money_month[k]))
                    else:
                        return -999999
            else:
                for k in keys:
                    if money_month[k]!=[]:
                        sum_money.append(sum(money_month[k]))
                    else:
                        return -999999
            #不计算于0相关的增长率
            ratio = cal_ratio(sum_money)

            return round(np.mean(ratio), 4) if ratio !=[] else -999999
        else:
            return -999999
    except:
        return -999999



def cal_ratio(list):
    ratio = []
    index_0 = [i for i,v in enumerate(list) if v==0.0]
    if len(index_0) ==1:
        tmp1 = list[0:index_0[0]]
        tmp2 = list[index_0[0] + 1:]
        if len(tmp1) >= 2:
            for j in xrange(len(tmp1) - 1):
                ratio.append((float(tmp1[j]))/(float(tmp1[j+1])) - 1)
        if len(tmp2) >= 2:
            for j in xrange(len(tmp2) - 1):
                ratio.append(float(tmp2[j])/float(tmp2[j+1]) - 1)
        return ratio
    elif len(index_0) >1:
        for i,v in enumerate(index_0):
            if i == 0:
                tmp = list[0:v]
                if len(tmp) >= 2:
                    for j in xrange(len(tmp)-1):
                        ratio.append((float(tmp[j])/float(tmp[j+1]))-1)

            elif i > 0 and i < (len(index_0)-1):
                tmp = list[index_0[i-1]+1:v]
                if len(tmp) >= 2:
                    for j in xrange(len(tmp)-1):
                        ratio.append(float(tmp[j])/float(tmp[j+1])-1)
            elif i == (len(index_0) -1):
                tmp1 = list[v+1:]
                tmp2 = list[index_0[i-1]+1:v]
                if len(tmp1) >= 2:
                    for j in xrange(len(tmp1)-1):
                        ratio.append(float(tmp1[j])/float(tmp1[j+1])-1)
                if len(tmp2) >=2:
                    for j in xrange(len(tmp2)-1):
                        ratio.append(float(tmp2[j])/float(tmp2[j+1])-1)
            else:
                pass
        return ratio
    else:
        for j in xrange(len(list)-1):
            ratio.append(float(list[j]/list[j+1])-1) #按照T1，T2，T3计算逻辑
        return ratio

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

result = Rule53_OrderAmount_FallingRate_Check_1()

